using System.Text.RegularExpressions;

namespace UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;

public sealed partial class PermissionCode
{
    public string Value { get; private set; }

    private PermissionCode(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentException("权限编码不能为空", nameof(value));

        if (!PermissionRegex().IsMatch(value))
            throw new ArgumentException("权限编码格式错误，应为'资源:操作'格式", nameof(value));

        Value = value;
    }

    [GeneratedRegex(@"^([a-z]+(\.[a-z]+(_[a-z]+)*){0,4})+:[a-zA-Z0-9]+$")]
    private static partial Regex PermissionRegex();

    /// <summary>
    /// 工厂方法
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static PermissionCode Create(string value) {System.Console.WriteLine($"value: {value}"); return new  PermissionCode(value);}

    /// <summary>
    /// 隐式转换为string
    /// </summary>
    /// <param name="code"></param>
    public static implicit operator string(PermissionCode code) => code.Value;

    /// <summary>
    /// 显式转换为PermissionCode，带验证逻辑
    /// </summary>
    /// <param name="value"></param>
    public static explicit operator PermissionCode(string value) => Create(value);

    /// <summary>
    /// 比较两个权限编码是否相等
    /// </summary>
    /// <param name="other"></param>
    /// <returns></returns>
    public bool Equals(PermissionCode? other) => 
        other is not null && Value == other.Value;
    
    /// <summary>
    /// 比较两个权限编码是否相等
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public override bool Equals(object? obj) =>
        obj is PermissionCode other && Equals(other);
    
    /// <summary>
    /// 获取哈希值
    /// </summary>
    /// <returns></returns>
    public override int GetHashCode() => Value.GetHashCode();

    /// <summary>
    /// 获取字符串表示形式
    /// </summary>
    /// <returns></returns>
    public override string ToString() => Value;

    /// <summary>
    /// 比较两个权限编码是否相等
    /// </summary>
    /// <param name="left"></param>
    /// <param name="right"></param>
    /// <returns></returns>
    public static bool operator ==(PermissionCode? left, PermissionCode? right) => 
        Equals(left, right);
    
    /// <summary>
    /// 比较两个权限编码是否不相等
    /// </summary>
    /// <param name="left"></param>
    /// <param name="right"></param>
    /// <returns></returns>
    public static bool operator !=(PermissionCode? left, PermissionCode? right) =>
        !Equals(left, right);

    
}